package com.cssw.fyzb.busi.api.user;


import com.cssw.fyzb.busi.service.user.UserService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Function(description = "同步用户数据至es", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户编号", required = true),
        @Parameter(name = "type", type = Type.Integer, description = "类型为all时，全部同步", required = true)
})
@Component
public class SyncUserToEs implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    private static final Logger logger = LoggerFactory.getLogger(UpdateAvatar.class);

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String type = request.getString("type");

        SimpleLock userLock = simpleLockFactory.getLock("SYNC_USER_" + userId);
        try {
            userLock.acquire();
            userService.syncUserToEs(userId, type);

            return Response.success();
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("操作失败");
        } finally {
            try {
                userLock.release();
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }
}
